package com.meilingcloud.research.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilingcloud.research.domain.RwsTopicUser;
import com.meilingcloud.research.mapper.RwsTopicUserMapper;
import com.meilingcloud.research.service.IRwsTopicUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 课题-成员 Service业务层处理
 *
 * @author chenl
 * @date 2021-03-23
 */
@Service
public class RwsTopicUserServiceImpl extends ServiceImpl<RwsTopicUserMapper, RwsTopicUser> implements IRwsTopicUserService {

    @Override
    public List<RwsTopicUser> queryList(RwsTopicUser rwsTopicUser) {
        LambdaQueryWrapper<RwsTopicUser> lqw = Wrappers.lambdaQuery();
        if (rwsTopicUser.getTopicId() != null) {
            lqw.eq(RwsTopicUser::getTopicId, rwsTopicUser.getTopicId());
        }
        if (rwsTopicUser.getUserId() != null) {
            lqw.eq(RwsTopicUser::getUserId, rwsTopicUser.getUserId());
        }
        return this.list(lqw);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addMember(List<RwsTopicUser> topicUsers) {
        if (CollectionUtil.isNotEmpty(topicUsers)) {
            this.remove(new LambdaQueryWrapper<RwsTopicUser>().eq(RwsTopicUser::getTopicId, topicUsers.get(0).getTopicId()));
            return this.saveBatch(topicUsers);
        }
        return false;
    }

    @Override
    public List<Long> getMembers(Long topicId) {
        RwsTopicUser topicUser = new RwsTopicUser();
        topicUser.setTopicId(topicId);
        return this.queryList(topicUser).stream().map(RwsTopicUser::getUserId).collect(Collectors.toList());
    }

}
